package com.lcb.manager.web;

import com.alibaba.fastjson.JSON;
import com.lcb.manager.entity.Address;
import com.lcb.manager.entity.News;
import com.lcb.manager.entity.Scientific;
import com.lcb.manager.repository.AddressRepository;
import com.lcb.manager.repository.NewsRepository;
import com.lcb.manager.repository.ScientificRepository;
import com.lcb.manager.vo.NewsVo;
import com.lcb.manager.vo.ScientificVo;
import com.lcb.manager.vo.WinNewsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("win")
public class WindowsController {

    @Autowired
    private NewsRepository newsRepository;

    @Autowired
    private AddressRepository addressRepository;

    @Autowired
    private ScientificRepository scientificRepository;

    //企业新闻接口
    @ResponseBody
    @RequestMapping(value = "/get_news_list", method = RequestMethod.GET)
    public String getNewsList() {
        WinNewsVo vo = new WinNewsVo();
        Address address = addressRepository.findById(1).orElse(null);
        if (address != null && address.isDisplayAddress()) {
            vo.setDisplayAddress(address.isDisplayAddress());
            vo.setText(address.getText());
            vo.setPictures(JSON.parseArray(address.getPictures(), String.class));
            vo.setNewsVoList(new ArrayList<>());
            return JSON.toJSONString(vo);
        } else {
            vo.setDisplayAddress(false);
            vo.setText("");
            vo.setPictures(new ArrayList<>());
            List<News> newsList = newsRepository.findAll();
            List<NewsVo> newsVoList = newsList.stream().map(NewsVo::fromEntity).collect(Collectors.toList());
            vo.setNewsVoList(newsVoList);
            return JSON.toJSONString(vo);
        }
    }

    //在建项目接口
    @ResponseBody
    @RequestMapping(value = "/get_scientific_list", method = RequestMethod.GET)
    public String getScientificList() {
        List<Scientific> scientificList = scientificRepository.findAll();
        scientificList.sort(Comparator.comparing(Scientific::getDate));
        List<ScientificVo> scientificVoList = scientificList.stream().map(ScientificVo::fromEntity).collect(Collectors.toList());
        return JSON.toJSONString(scientificVoList);
    }

}
